package top.glkj.hms.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import top.glkj.hms.entity.User;
import top.glkj.hms.service.UserService;
import top.glkj.hms.utils.StaticValue;
import top.glkj.hms.utils.Status;

/**
 * @author : xgl
 * @version : 0.0.1
 * @date :2020/11/28 1:51
 */
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {

    private final UserService userService;

    @Autowired
    public UserAuthenticationProvider(UserService userService) {
        this.userService = userService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取表单输入中返回的用户名
        String userName = (String) authentication.getPrincipal();
        // 获取表单中输入的密码
        String password = (String) authentication.getCredentials();
        // 查询用户是否存在
        User user = (User) userService.loadUserByUsername(userName);
        if (user == null) {
            throw new UsernameNotFoundException(userName + StaticValue.USERNAME_NOTFOUND);
        }
        // 我们还要判断密码是否正确，这里我们的密码使用BCryptPasswordEncoder进行加密的
        if (!new BCryptPasswordEncoder().matches(password, user.getPassword())) {
            throw new BadCredentialsException(userName + StaticValue.PASSWORD_IS_FAIL);
        }
        if (user.isDel()) {
            throw new AccountStatusException(userName + StaticValue.USER_IS_DELETE) {
            };
        }
        // 还可以加一些其他信息的判断，比如用户账号已停用等判断
        if (!user.getStatus().equals(Status.Enable)) {
            throw new AccountStatusException(userName + "被" + user.getStatus().getDescription()) {
            };
        }
        // 进行登录
        return new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
